﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using System.IO;

/// <summary>
/// CommonClass 的摘要说明
/// </summary>
public class CommonClass
{
    private const string KEY_64 = "78945612";
    private const string IV_64 = "78945612"; //注意了，是8个字符，64位
    /// <summary>
    /// 传入字符串，在后面加后辍,读取web.Config里的RewriterType
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string Url(string str)
    {
        if (str == "") return str;
        string Result = "";
        try
        {
            Result = str + CommonClass.ReWebConfig("RewriterType");
        }
        catch
        {
            Result = "";
        }
        return Result;
    }

    /// <summary>
    /// 字符串处理 过滤or,and ',&,+,,,'',
    /// </summary>
    /// <returns></returns>
    public static string newstr(string str)
    {
        //过滤or,and ',&,+,,,'',
        String nstr = str.Replace("=", "").Replace(" ", "").Replace("'", "").Replace("&", "").Replace(",", "").Replace("''", "");
        return nstr;
    }


    /// <summary>
    /// 替换HTML标签
    /// </summary>
    /// <param name="strContent"></param>
    /// <returns></returns>
    public static string HtmlEncrypt(string strContent)
    {

        strContent = strContent.Replace("&", "&amp;");
        strContent = strContent.Replace("´", "＇");
        strContent = strContent.Replace("<", "&lt;");
        strContent = strContent.Replace(">", "&gt;");
        strContent = strContent.Replace("chr(60)", "&lt;");
        strContent = strContent.Replace("chr(37)", "&gt;");
        strContent = strContent.Replace("\"", "&quot;");
        strContent = strContent.Replace("<br/>", "\n");
        strContent = strContent.Replace(" ", "&nbsp;");
        return strContent;

    }

    /// <summary>
    /// 替换为HTML
    /// </summary>
    /// <param name="strContent"></param>
    /// <returns></returns>
    public static string Encrypt_Html(string strContent)
    {
        strContent = strContent.Replace("&amp;", "&");
        strContent = strContent.Replace("＇", "´");
        strContent = strContent.Replace("&lt;", "<");
        strContent = strContent.Replace("&gt;", ">");
        strContent = strContent.Replace("&lt;", "chr(60)");
        strContent = strContent.Replace("&gt;", "chr(37)");
        strContent = strContent.Replace("&quot;", "\"");
        strContent = strContent.Replace("\n", "<br/>");
        strContent = strContent.Replace("&nbsp;", " ");
        return strContent;
    }







    /// <summary>
    /// 过滤script危险字符
    /// </summary>
    /// <param name="html"></param>
    /// <returns></returns>
    public static string valiScript(string html)
    {
        Regex regex1 = new Regex(@"<script[\s\S]+</script *>", RegexOptions.IgnoreCase);
        Regex regex2 = new Regex(@"href *= *[\s\S]*script *:", RegexOptions.IgnoreCase);
        Regex regex3 = new Regex(@"on[\s\S]*=", RegexOptions.IgnoreCase);
        html = regex1.Replace(html, "");
        //过滤<script></script>标记  
        html = regex2.Replace(html, ""); //过滤href=Javascript: (<A>) 属性   
        html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件   
        return html;
    }



    /// <summary>
    ///检查字符串，看有没有非法字符不允许输入已|分割
    /// 
    /// 
    ///
    /// </summary>
    public static void check_str(string str)
    {
        if (str != "")
        {
            string Illegal_Str = ",|&|+|'|\"|or|and|";
            string[] newstr = Illegal_Str.Split('|');
            for (int i = 0; i < (newstr.Length - 1); i++)
            {
                if (str.IndexOf(newstr[i]) != -1)
                {
                    System.Web.HttpContext.Current.Response.Write("<script>alert('含有非法字符！');history.back()</script>");
                }
            }
        }
    }


    public CommonClass()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    #region MD5加密
    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="Password">需要加密字符串</param>
    /// <returns></returns>
    public static String Encrypt(string Password)
    {
        Byte[] clearBytes = new UnicodeEncoding().GetBytes(Password);
        Byte[] hashedBytes = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(clearBytes);
        return BitConverter.ToString(hashedBytes);
    }

    #endregion


    public static string Encode(string data)
    {

        byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);

        byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);



        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

        int i = cryptoProvider.KeySize;

        MemoryStream ms = new MemoryStream();

        CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

        StreamWriter sw = new StreamWriter(cst);

        sw.Write(data);

        sw.Flush();

        cst.FlushFinalBlock();

        sw.Flush();

        return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);



    }



    public static string Decode(string data)
    {

        byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);

        byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

        byte[] byEnc;

        try
        {

            byEnc = Convert.FromBase64String(data);

        }

        catch
        {

            return null;

        }

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();

        MemoryStream ms = new MemoryStream(byEnc);

        CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);

        StreamReader sr = new StreamReader(cst);

        return sr.ReadToEnd();

    }



    #region 转换特殊字符

    public static string EncodeHtml(string Content)
    {
        try
        {
            if (Content != string.Empty)
                Content = Content.Replace("<", "&lt;");
            Content = Content.Replace(">", "&gt;");
            Content = Content.Replace(((char)34).ToString(), "&quot;");
            Content = Content.Replace(((char)34).ToString(), "&#39;");
            Content = Content.Replace("'", "&quot;");
            //Content = Content.Replace(((char)32).ToString(), "&nbsp;");
            //Content = Content.Replace(((char)9).ToString(), "&nbsp;");
            //Content = Content.Replace(((char)13).ToString(), "&nbsp;");
            Content = Content.Replace(((char)10).ToString(), "<BR>");
        }
        catch
        {
            return Content;
        }
        return Content;
    }

    #endregion


    #region 获取WEB.Config的关键字 web.config中key的名称

    /// <summary>
    /// 获取WEB.Config的关键字
    /// </summary>
    /// <param name="key">web.config中key的名称</param>
    /// <returns></returns>

    public static string ReWebConfig(string key)
    {
        string Re;
        try
        {
            if (ConfigurationManager.AppSettings[key] == null)
            {
                Re = "Err";
            }
            else
            {
                Re = ConfigurationManager.AppSettings[key].ToString();
            }
        }
        catch
        {
            //Errors.InsertError(Ex.Message, 0);
            Re = "Err";
        }
        return Re;

    }

    #endregion


    #region 获取用户IP

    /// <summary>
    /// 获取用户IP
    /// </summary>
    /// <returns></returns>
    public static string netIP()
    {
        try
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }
        catch
        {
            return "";
        }
        finally
        {

        }
    }

    #endregion


    #region 分割字符串

    /// <summary>
    /// 分隔字符串
    /// </summary>
    /// <param name="str">字符串</param>
    /// <param name="separator">字符串分隔符</param>
    /// <returns></returns>
    public static string[] SplitString(string str, string separator)
    {
        string tmp = str;
        Hashtable ht = new Hashtable();
        int i = 0;
        int pos = tmp.IndexOf(separator);
        while (pos != -1)
        {
            ht.Add(i, tmp.Substring(0, pos));
            tmp = tmp.Substring(pos + separator.Length);
            pos = tmp.IndexOf(separator);
            i++;
        }
        ht.Add(i, tmp);
        string[] array = new string[ht.Count];
        for (int j = 0; j < ht.Count; j++)
            array[j] = ht[j].ToString();

        return array;
    }

    #endregion


    #region 截取字符串长度有小于符号

    /// <summary>
    /// 截取字符串长度有小于符号
    /// </summary>
    /// <param name="inputString"></param>
    /// <param name="len"></param>
    /// <returns></returns>
    public static string CutString(string inputString, int len)
    {

        ASCIIEncoding ascii = new ASCIIEncoding();
        int tempLen = 0;
        string tempString = "";
        byte[] s = ascii.GetBytes(inputString);
        for (int i = 0; i < s.Length; i++)
        {
            if ((int)s[i] == 63)
            {
                tempLen += 2;
            }
            else
            {
                tempLen += 1;
            }

            try
            {
                tempString += inputString.Substring(i, 1);
            }
            catch
            {
                break;
            }

            if (tempLen > len)
                break;
        }
        //如果截过则加上半个省略号
        byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
        if (mybyte.Length > len)
            tempString += "…";
        return tempString;
    }

    #endregion


    #region 截取字符串长度无小于符号
    /// <summary>
    /// 截取字符串长度无小于符号
    /// </summary>
    /// <param name="sTitle">文本内容</param>
    /// <param name="sInt">字符长度</param>
    /// <returns></returns>

    public static string GetContentLength(string sTitle, int sInt)
    {
        if (sTitle.Length > sInt)
        {
            return sTitle.Substring(0, sInt);
        }
        else
        {
            return sTitle;
        }
    }

    #endregion


    #region 判断是否为数字
    //判断是否为数字
    /// <summary>
    /// 判断是否为数字
    /// </summary>
    /// <param name="Str"></param>
    /// <returns></returns>
    public static bool StrIsInt(string Str)
    {
        try
        {
            Int32.Parse(Str);
            return true;
        }
        catch
        {
            bool flag = false;
            return flag;
        }
    }
    #endregion


    #region 截取IP字符前3段

    /// <summary>
    /// 截取IP字符前3段
    /// </summary>
    /// <param name="_ip">string 类型IP地址</param>
    /// <returns></returns>
    public static string GetEncryptIP(string _ip)
    {
        string _Point = _ip;
        string[] PointArray = _Point.Split('.');
        return PointArray[0] + "." + PointArray[1] + "." + PointArray[2] + ".*";
    }

    #endregion


    #region  搜索关键字变颜色
    /// <summary>
    /// 搜索关键字变颜色
    /// </summary>
    /// <param name="str">字符串</param>
    /// <param name="keys">关键字</param>
    /// <returns></returns>
    public static string keysColor(string str, string keys)
    {
        if (str != "")
        {
            if (keys != "")
            {

                return str.Replace(keys, "<span style='color:red'>" + keys + "</span>").ToString();
            }
            else
            {
                return str;
            }
        }
        else
        {
            return "";
        }
    }

    #endregion

    #region  过滤所有ＨＴＭＬ标记
    /// <summary>
    /// 过滤所有ＨＴＭＬ标记
    /// </summary>
    /// <param name="Htmlstring"></param>
    /// <returns></returns>
    public static string RemoveHtml(string Htmlstring) //去除HTML标记 
    {
        //删除脚本 
        Htmlstring = Regex.Replace(Htmlstring, @"(?s)<script.*?>.*?</script>", "", RegexOptions.IgnoreCase);
        //删除样式 
        Htmlstring = Regex.Replace(Htmlstring, @"(?s)<style.*?>.*?</style>", "", RegexOptions.IgnoreCase);
        //删除HTML 
        Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);

        Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
        Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);

        Htmlstring = Htmlstring.Replace("<", "〈");
        Htmlstring = Htmlstring.Replace(">", "〉");
        Htmlstring = Htmlstring.Replace("\r\n", "");
        Htmlstring = Htmlstring = Htmlstring.Replace(" ", "");
        Htmlstring = Htmlstring.Replace("“", "“");
        Htmlstring = Htmlstring.Replace("”", "”");
        Htmlstring = Htmlstring.Replace("&", "&");
        Htmlstring = System.Web.HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

        return Htmlstring;
    }
    #endregion

    /// <summary>
    /// 获取Request的参数
    /// </summary>
    /// <param name="obj">获取参数</param>
    /// <param name="SetObj">输出参数</param>
    public static void Request(string obj, out string SetObj)
    {
        SetObj = "";
        if (HttpContext.Current.Request[obj] != null)
        {
            if (HttpContext.Current.Request[obj].ToString().Trim().ToLower() != "")
            {
                SetObj = HttpContext.Current.Request[obj].ToString().Trim();

            }
        }

    }


    /// <summary>
    /// 功能描述：返回不重复随机数数组
    /// </summary>
    /// <param name="Number">   随机数个数</param>
    /// <param name="minNum">随机数下限</param>
    /// <param name="maxNum">随机数上限</param>
    /// <returns></returns>
    public static int[] GetRandomArray(int Number, int minNum, int maxNum)
    {
        int j;
        int[] b = new int[Number];
        Random r = new Random();
        for (j = 0; j < Number; j++)
        {
            int i = r.Next(minNum, maxNum + 1);
            int num = 0;
            for (int k = 0; k < j; k++)
            {
                if (b[k] == i)
                {
                    num = num + 1;
                }
            }
            if (num == 0)
            {
                b[j] = i;
            }
            else
            {
                j = j - 1;
            }
        }
        return b;
    }

    /// <summary>
    /// 截取字符串
    /// </summary>
    /// <param name="Str">字符串</param>
    /// <param name="Instr">截取字串长度 [从右至左]</param>
    /// <param name="RplaceStr">替换字符串</param>
    /// <returns></returns>
    public static string GetStrInstr(string Str, int Instr, string RplaceStr)
    {
        if (Str.Length <= Instr)
        {
            return Str;
        }
        else
        {
            return RplaceStr + Str.Substring(Str.Length - Instr, Instr);
        }
    }

    #region 检查DATASET里面是否存在某列
    /// <summary>
    /// 检查DATASET里面是否存在某列
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="ColumnsName"></param>
    /// <returns></returns>
    public static bool IsColumns(DataSet ds, string ColumnsName)
    {
        bool isok = false;
        try
        {
            isok = ds.Tables[0].Columns.Contains(ColumnsName);

        }
        finally
        {

        }
        return isok;
    }
    #endregion


    /// <summary>
    /// 判断是否转换为数字型,返回BOOL
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool isNumber_bool(string str)
    {
        try
        {
            int.Parse(str);
            return true;
        }
        catch
        {
            return false;
        }

    }

    /// <summary>
    /// 判断是否转换为数字型,返回int
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static int isNumber_int(string str)
    {
        int returnValue = 0;
        try
        {

            returnValue = int.Parse(str);
        }
        catch
        {
        }
        return returnValue;
    }


    /// <summary>
    /// 判断是否转换为decimal型,返回decimal
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static decimal isNumber_decimal(string str)
    {
        decimal returnValue = 0;
        try
        {

            returnValue = decimal.Parse(str);
        }
        catch
        {
        }
        return returnValue;
    }
    /// <summary>
    /// 文件编码
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static string FileType_Encoding(string type)
    {
        string Result = ",";
        foreach (string str in CommonClass.SplitString(type, ","))
        {
            if (str == "")
            {
                break;
            }
            switch (str.ToLower().Trim())
            {
                case "jpg":
                    Result += "255216,";
                    break;
                case "jpeg":
                    Result += "255216,";
                    break;
                case "gif":
                    Result += "7173,";
                    break;

                case "bmp":
                    Result += "6677,";
                    break;

                case "png":
                    Result += "13780,";
                    break;

                case "exe":
                    Result += "7790,";
                    break;

                case "rar":
                    Result += "8297,";
                    break;
            }

        }
        return Result;
    }
    /// <summary>
    /// 返回当前星期几
    /// </summary>
    /// <param name="str">string类型</param>
    /// <returns></returns>
    public static string weekfun(string str)
    {
        string weekstr = "";
        switch (str)
        {
            case "Monday": weekstr = "星期一"; break;
            case "Tuesday": weekstr = "星期二"; break;
            case "Wednesday": weekstr = "星期三"; break;
            case "Thursday": weekstr = "星期四"; break;
            case "Friday": weekstr = "星期五"; break;
            case "Saturday": weekstr = "星期六"; break;
            case "Sunday": weekstr = "星期日"; break;
        }
        return weekstr;

    }
    /// <summary>
    /// 在数字前面加零
    /// </summary>
    /// <param name="num"></param>
    /// <param name="len"></param>
    /// <returns></returns>
    public static string AddStr(int num, int len)
    {
        string Result = "";
        if (num.ToString().Trim().Length > 0)
        {
            string str = "";
            for (int n = num.ToString().Trim().Length; n < len; n++)
            {
                str += "0";
            }
            Result = str + num.ToString();
        }
        return Result;
    }


}
